package servlets;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/loginServlet"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method") ;
        if("login".equals(method)){
            this.login(req, resp);
        }
        else if("logout".equals(method)){
            this.logout(req, resp);
        }
    }


    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.得到用户名
        String username = req.getParameter("username") ;
        String password = req.getParameter("password") ;
        String ck = req.getParameter("ck") ;

        System.out.println("ck = " + ck);

        //2.调用shiro api
        Subject subject = SecurityUtils.getSubject() ;

        UsernamePasswordToken token = new UsernamePasswordToken(username,password) ;

        try {
            if(ck!=null){
                //设置记住我
                token.setRememberMe(true);

            }
            subject.login(token);
            resp.sendRedirect("/shiroweb2/list.jsp");
        } catch (Exception e){
            req.setAttribute("error","用户名或者密码不对！");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }


    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //
        Subject subject = SecurityUtils.getSubject() ;
        subject.logout();
        resp.sendRedirect("/shiroweb2/login.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
